#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#include "e2pfs-utils.h"

int main(int argc, char* argv[])
{
	int fd;
	int ret = 0;
	int padding_size = 0;
	char* padding_data = NULL;
	struct e2pfs_super_block sb;

	if (argc != 2) {
		printf("Usage: mkfs-e2pfs <device>\n");
		return -1;
	}

	fd = open(argv[1], O_RDWR);
	if (fd == -1) {
		printf("Error opening the device\n");
		return -1;
	}

	memset(&sb, 0, sizeof(sb));

	sb.magic = E2PFS_MAGIC;
	sb.block_size = E2PFS_BLOCK_SIZE;
	sb.root_inode = E2PFs_ROOT_INODE;
	sb.free_blocks[0] = 1;

	ret = write(fd, (char*)&sb, sizeof(sb));
	if (ret != sizeof(sb)) {
		printf("write super block failed! ret = %d\n", ret);
		close(fd);
		return -1;
	}

	padding_size = E2PFS_BLOCK_SIZE - sizeof(sb);
	padding_data = malloc(padding_size);
	if(!padding_data) {
		printf("create super block padding data failed\n");
		close(fd);
		return -1;
	}

	memset(padding_data, 0, padding_size);

	ret = write(fd, padding_data, padding_size);
	if (ret != padding_size) {
		printf("write super block padding data failed! ret = %d\n", ret);
		close(fd);
		return -1;
	}

	close(fd);

	return 0;

}
